package com.joyrec.util.db.mongo

import scala.Array.canBuildFrom
import scala.collection.convert.WrapAsJava

import com.mongodb.Mongo
import com.mongodb.MongoOptions
import com.mongodb.ServerAddress

import ws.very.util.akka.util.Confable

trait Mongoable extends Confable {
  
  def dbClustersCons : String
  def dbMaxConnectionsCons : String
  def dbMaxWaittimeCons: String
  def threadsForConn : Int
  

  object DB extends WrapAsJava {
    val serverAddressList = conf.getString(dbClustersCons).split(",").map { address =>
      val Array(ip, port) = address.split(":")
      new ServerAddress(ip, port.toInt)
    }.toList
    lazy val reader = apply(serverAddressList)
    lazy val writer = reader

    private def apply(ipAndPort: List[ServerAddress]) = {
      val option = new MongoOptions
      option.autoConnectRetry = true
      option.connectionsPerHost = conf.getInt(dbMaxConnectionsCons)
      option.maxWaitTime = conf.getInt(dbMaxWaittimeCons)
      option.slaveOk = false
      option.safe = true
      // option.fsync=true
      option.threadsAllowedToBlockForConnectionMultiplier = threadsForConn
      new Mongo(ipAndPort, option)
    }
  }

  trait DBConfig {
    protected def reader: Mongo = DB.reader
    protected def writer: Mongo = DB.writer
  }

  protected val dbPrefix: String

}